import * as processtypeService from '../services/processtype'

export default {
  namespace: 'processtype',
  state: {
    list: [],
    total: null,
    page: null,
  },
  reducers: {
    save(state, { payload: { data: list, total, page } }) {
      return { ...state, list, total, page }
    },
  },
  effects: {
    * fetch({ payload: { page = 1 } }, { call, put }) {
      const { data } = yield call(processtypeService.fetch, { page })
      yield put({
        type: 'save',
        payload: {
          data,
          total: parseInt(data.total),
          page: parseInt(data.pages),
        },
      })
    },
    * remove({ payload: id }, { call, put }) {
      yield call(processtypeService.remove, id)
      yield put({ type: 'reload' })
    },
    * patch({ payload: { id, values } }, { call, put }) {
      yield call(processtypeService.patch, id, values)
      yield put({ type: 'reload' })
    },
    * create({ payload: values }, { call, put }) {
      values.systemCode = values.systemCode.label.join('')
      const result = yield call(processtypeService.create, values)
      if (result.data.code === 400) {
        throw new Error(result.data.message)
      }
      yield put({ type: 'add', payload: result })
    },
    * reload(action, { put, select }) {
      const page = yield select(state => state.processtype.page)
      yield put({ type: 'fetch', payload: { page } })
    },
    * add({ payload: result }, { call, put }) {
      yield put({ type: 'reload' })
    },
  },
  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname, query }) => {
        if (pathname === '/processtype') {
          if (query === undefined) {
            query = { page: 1 }
          }
          dispatch({ type: 'fetch', payload: query })
        }
      })
    },
  },
}
